package org.openclinic.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.openclinic.exception.AbstractExceptionHandler;
import org.openclinic.service.AppointmentService;
import org.openclinic.service.CustomerService;
import org.openclinic.service.HealthProfessionalService;
import org.openclinic.service.MedicalSpecialtyService;
import org.openclinic.to.ReportParametersTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ReportsController extends AbstractExceptionHandler {

	@Autowired
	private AppointmentService appointmentService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private HealthProfessionalService healthProfessionalService;
	
	@Autowired
	private MedicalSpecialtyService medicalSpecialtyService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
	}
	
	@RequestMapping(value = "/reports.do", method = RequestMethod.GET)
	public ModelAndView initReport() {	
		ModelAndView mav = new ModelAndView("report.view");
		mav.addObject("customerList", customerService.list());
		mav.addObject("professionalList", healthProfessionalService.list());
		mav.addObject("specialtyList", medicalSpecialtyService.list());
		
		return mav;
	}
	
	@RequestMapping(value = "/reports/results.do", method = RequestMethod.GET)
	public String initResults() {
		return "report-results.jsp";
	}
	
	@RequestMapping(value = "/reports/results.do", method = RequestMethod.POST)
	public ModelAndView showResults(ReportParametersTO parameters, BindingResult validationResult) {
		ModelAndView mav = new ModelAndView("report-results.jsp");
		mav.addObject("resultsList", appointmentService.getReportResults(parameters));
		
		return mav;
	}
}
